import {
  say,
  filterCharacter,
  uniqueArr,
  getUrlParams,
} from './util.js'
import rangeParser from './range-parser.js'
import Queue from './queue.js';

var OPTION = {
  age: 3,
  strict: true, // 严格模式：按错不发音
};

const defaultRange = 'a-z';
const defaultParams = {
  range: defaultRange,
  num: 3,
  repeat: 1,
};
var CONFIG = {
  3: {
    total: 3,
    step: .3,
    ratio: 0.01,// 击键成功次数与速度（step）之间的调整系数
    repeat: 1, // 朗读重复次数
  },
};
var config = CONFIG[OPTION.age];
var stage;
var stageHeight;
var total = config.total || 10;
var fontSize = 100;
var step = config.step || 1;// speed
var ratio = config.ratio;
var repeat = config.repeat;
var fontBoundWidth;
let isPageVisible =  document.hidden || false;

// 速度 = 成功次数 * 系数 + base step
function adjustSpeed(step, success, ratio) {
  return step + success * ratio;
}

(function (ARE) {
  var Stage = ARE.Stage;

  //webgl不支持渲染Text，你可以使用ARE.Label
  stage = new Stage("#ourCanvas", true);
  // stage.debug = true;
  stageHeight = stage.height;
  fontBoundWidth = stage.width - fontSize;
  var FREQUENCY = 1000;
  var success = 0; // 击键成功次数

  function start(stage, FREQUENCY) {

    var setting = Object.assign({}, defaultParams, getUrlParams());// 从 url 中获取配置
    var rangeSetting = setting.range ;
    var totalSetting = parseInt(setting.num || setting.total, 10);// 暂时兼容 `total`
    var repeatSetting = parseInt(setting.repeat, 10) || repeat;
    var group1 = 'asdfghjkl';

    var range = uniqueArr(filterCharacter(rangeParser( rangeSetting ))) || [];// 此处需要过滤重复

    if (!isNaN(totalSetting) ){
      total = totalSetting;
    }

    const queue = new Queue({
      stage,
      stageHeight,
      range: range.length ? range : group1.split(''),
      total,
    });
    // 生成字母
    setInterval(function () {
      queue.spawn(fontBoundWidth);
    }, FREQUENCY);

    stage.onTick(function () {
      if( isPageVisible ){ return; } // tab 隐藏时，不再处理逻辑
      const speed = adjustSpeed(step, success, ratio);
      queue.senesce({
        step: speed,
      });
    });

    stage.setFPS(1);
    // binding events
    document.onkeydown = function (e) {
      const charCode = e.which;
      const char = String.fromCharCode(charCode).toLowerCase();
      if (queue.isExist(char)) {
        const src = `${AUDIO_HOST_PREFIX}/${char}.mp3`;
        say(src, repeatSetting);
        queue.hide( char );
        success++;
      }
    };

    window.addEventListener('hashchange', ()=>{
      // todo: 读取新的参数
      window.location.reload();
    });

    document.addEventListener("visibilitychange", function(){
      isPageVisible = document.hidden;
    });
  }

  start(stage, FREQUENCY);
})(ARE);
